<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\api;

use app\common\model\GoodsOrder;
use app\common\model\Goods;
use app\common\model\Channel;
use Webman\RateLimiter\Limiter;

class OrderService
{
    /**
     * 创建订单
     * @param array $post
     */
    public function createOrder(array $post)
    {
        $goods = Goods::where('status', 1)->find($post['goods_id']);
        $ip    = request()->ip();
        if (conf("order_create_limit_time_by_ip")) {
            Limiter::check($ip, 1, conf("order_create_limit_time_by_ip"), trans('please_do_not_request_frequently'));
        }
        $validate = new \app\api\validate\OrderValidate;
        $validate->scene('create')->failException(true)->check($post);
        $post["create_ip"]        = $ip;
        $post["goods_id"]         = $goods->getAttr('id');
        $post["goods_name"]       = $goods->getAttr('name');
        $post["goods_price"]      = $goods->getAttr('price');
        $post["goods_cost_price"] = $goods->getAttr('cost_price');
        $post["quantity"]         = 1;

        // 计算总价
        $post["total_price"] = round($post["goods_price"] * $post["quantity"], 2);

        $channel = Channel::where(['id' => inputs("pid/d", 0), "status" => 1])->findOrEmpty();
        if ($channel->isEmpty()) {
            throw new \Exception("支付接口不存在！");
        }


        // 官方支付网关下的所有账号 accounts
        $accounts = $channel->accounts()->where(['status' => 1])->select();

        if (empty(count($accounts))) {
            throw new \Exception("当前支付接口没有可用的账号！");
        }

        // 网关账号 随机取一个
        $account                    = (object) $accounts[array_rand($accounts->toArray())];
        $post["paytype"]            = $channel->paytype;
        $post["channel_id"]         = $channel->id;
        $post["channel_account_id"] = $account->id;

        if ($post["total_price"] < 0) {
            throw new \Exception("商品价格错误，请联系平台！");
        }

        $post["status"] = 0;
        try {
            $result = GoodsOrder::create($post);
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        return [
            "id"       => $result->id,
            "trade_no" => $result->trade_no,
            "price"    => $result->total_price,
        ];
    }

}